package com.qdlc.p2p.dal.mybatis;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;

import com.qdlc.p2p.common.constant.Global;


/**
 * StatementHandler拦截器
 * @author linya 2016-04-11 19:50:49
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class TablePrefixStatementHandlerInterceptor implements Interceptor {

	private static final String TABLE_PREFIX = "\\{prefix\\}";
	
	// 默认定义MetaObject使用时的ObjectFactory和ObjectWrapperFactory两个参数
	private ObjectFactory objectFactory = new DefaultObjectFactory();
	private ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
	
	public Object intercept(Invocation invocation) throws Throwable {
		
		//获取参数处理器
		StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
		BoundSql boundSql = statementHandler.getBoundSql();
		
		//获取sql
		String sql = boundSql.getSql();
		String newSql = sql.replaceAll(TABLE_PREFIX, Global.DB_PREFIX);
		MetaObject metaObject = MetaObject.forObject(boundSql, objectFactory, objectWrapperFactory);
		metaObject.setValue("sql", newSql);
		
		return invocation.proceed();
	}
	
	@Override
	public Object plugin(Object target) {
		if (target instanceof StatementHandler) {
			return Plugin.wrap(target, this);
		}
		return target;
	}

	@Override
	public void setProperties(Properties properties) {
		
	}
	
}
